package edu.esiag.isidis.fi.lb.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import edu.esiag.isidis.fi.lb.interfaces.IRegister;
public class Register<TypeEntity> implements IRegister<TypeEntity> {

	private static final String DISABLE_METHOD = "disable";
	private static final String ACTIVATE_METHOD = "activate";
	private static final String GET_ID_METHOD = "getIdentifier";
	private List<TypeEntity> liste = Collections.synchronizedList(new ArrayList<TypeEntity>());
	
	public void register(TypeEntity entity) {
		synchronized (liste) {
			liste.add(entity);
		}
	}
	public List<TypeEntity> getEntities(){
		List<TypeEntity> entities = new ArrayList<TypeEntity>();
		for(TypeEntity entity : liste){
			entities.add(entity);
		}
		return entities;
	}
	public void activeEntity(Object id) {
		for(TypeEntity entity : liste){
			try {
				Method method = entity.getClass().getDeclaredMethod(GET_ID_METHOD);
				Object IdEntity = method.invoke(entity);
				if(IdEntity.equals(id))
				{
					method = entity.getClass().getDeclaredMethod(ACTIVATE_METHOD);
					method.invoke(entity);
				}
				else
				{
					method = entity.getClass().getDeclaredMethod(DISABLE_METHOD);
					method.invoke(entity);
				}
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}
